package com.coder.rental.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.User;
import com.coder.rental.service.IRoleService;
import com.coder.rental.service.IUserService;
import com.coder.rental.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tuboyuan
 * @since 2025-09-04
 */
@RestController
@RequestMapping("/rental/user")
public class UserController {
    @Resource
    private IUserService iUserService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private IRoleService roleService;
    @GetMapping
    public Result<List<User>> list(){
        return Result.success(iUserService.list());
    }
    @PostMapping("/{page}/{size}")
    public Result page(@PathVariable int page, @PathVariable int size,@RequestBody User user){
        return Result.success(iUserService.searchByPage(new Page<>(page,size),user));
    }

    /**
     * 保存用户信息
     * @param user 用户对象，包含用户名、密码等信息
     * @return Result 操作结果，包含成功或失败信息
     */
    @PostMapping
    public Result save(@RequestBody User  user){
        // 检查用户名是否已存在
        User user1=iUserService.selectByUsername(user.getUsername());
        if(user1!=null){
            return Result.fail().setMessage("用户名已存在");
        }else {
            // 对用户密码进行加密处理
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            // 设置用户为非管理员角色
            user.setIsAdmin(0);
            // 如果用户头像为空，则设置默认头像
            if (StrUtil.isEmpty(user.getAvatar())){
                user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            }
            // 保存用户信息并返回操作结果
            return iUserService.save(user)?Result.success().setMessage("添加成功"):Result.fail().setMessage("添加失败");
        }
    }

    @PutMapping
    public Result update(@RequestBody User user){
        User u=iUserService.selectByUsername(user.getUsername());
        if(u!=null&& Objects.equals(u.getId(),user.getId())){
            return Result.fail().setMessage("用户名已存在");
        }
        if(StrUtil.isEmpty(user.getAvatar())){
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        }
        return iUserService.updateById(user)?Result.success().setMessage("修改成功"):Result.fail().setMessage("修改失败");
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        return iUserService.removeById(id)?Result.success().setMessage("删除成功"):Result.fail().setMessage("删除失败");
    }
    @GetMapping("role/{userId}")
    public Result selectRoleByUserId(@PathVariable Integer userId){
        return Result.success(roleService.selectRoleIdByUserId(userId));
    }
    @GetMapping("bind/{userId}/{roleIds}")
    public Result bindRole(@PathVariable Integer userId,
                           @PathVariable String roleIds){
        List<Integer> list = Arrays.stream(roleIds.split(","))
                .map(Integer::parseInt)
                .toList();
        return iUserService.bindRole(userId,list)?Result.success():Result.fail();

    }


}
